package com.sidom.movieIndexer.service.file;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import static org.apache.commons.io.FileUtils.listFiles;
import static org.apache.commons.lang.Validate.notNull;
import static org.apache.commons.lang.Validate.isTrue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;

import com.sidom.movieIndexer.domain.Movie;
import com.sidom.movieIndexer.domain.file.MovieFile;

/**
 * {@inheritDoc}.
 * 
 * @author Siebe
 */
@Repository
public class FileServiceImpl implements FileService{
	/**
	 * Logger for {@link FileServiceImpl}.
	 */
	private Log log = LogFactory.getLog(FileServiceImpl.class);
	
	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")//FileUtils doesn't use generics
	@Override
	public List<Movie> getVideoFiles(final String path, final Set<String> extensions) {
		log.info("Getting files from path: " + path + " with extensions: " + extensions);
		notNull(path, "Path should not be null");
		isTrue(new File(path).exists(), "path should exist");
		notNull(extensions, "Extensions can not be null");
		
		log.info("Getting files from path: " + path);
		File file = new File(path);
		Collection<File> files = listFiles(file, extensions.toArray(new String[extensions.size()]), true);
		log.trace("Found movie files: " + files);
		return convertCollection(files);
	}
	
	/**
	 * Converts a {@link Collection} of {@link File}s to a {@link Set} of {@link Movie}s.
	 * @param files A {@link Collection} of {@link File}s
	 * @return A {@link Set} of {@link Movie}s
	 */
	private List<Movie> convertCollection(final Collection<File> files){
		List<Movie> movies = new ArrayList<Movie>();
		for(File file : files){
			Movie movie = new Movie();
			MovieFile movieFile = new MovieFile(file);
			movie.setMovieFile(movieFile);
			movies.add(movie);
		}
		return movies;
	}
}
